package com.ludomancy.gamelib;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;

public class ImageStrip 
{	
	private int rowSize = 0;
    private Image masterImage;
	public int frameWidth = 0;
	public int frameHeight = 0;
	private int frameCount = 0;


	public ImageStrip(Image image, int frameWidth, int frameHeight)
	{
		this(image, frameWidth, frameHeight, 50000);
	}
	
	public ImageStrip(Image image, int frameWidth, int frameHeight, int maxFrames) 
	{
		this.frameWidth = frameWidth;
		this.frameHeight = frameHeight;
		rowSize = image.getWidth(null)/frameWidth;
		frameCount = Math.min(rowSize * (image.getHeight(null)/frameHeight), maxFrames);
		masterImage = image;
	}
	
	public int[] getBitmask(int frame, int x, int y, int w, int h)
	{
		// intersect subarea with the frame area
		Rectangle frameArea = new Rectangle(0,0,frameWidth, frameHeight);
		Rectangle subArea = new Rectangle(x,y,w,h);
		Rectangle result = frameArea.intersection(subArea);
		if(result.height >0 && result.width > 0)
		{
			// find out in which row the frame is in
			int row = (frame/rowSize)*frameHeight;
			// find out in which cell the frame is in the row
			int cell = (frame % rowSize)*frameWidth;
			
			return ImageManipulation.extractBitmask(masterImage, result.x + cell, result.y + row, result.width, result.height);
		}
		System.err.println("ImageStrip::getBitmask areas do not overlap");
		return null;
	}
	
	public int getImageCount()
	{
		return frameCount;
	}
	
	public void paint(Graphics g, int frame, int x, int y, int anchor)
	{
		// find out in which row the frame is in
		int row = (frame/rowSize)*frameHeight;
		// find out in which cell the frame is in the row
		int cell = (frame % rowSize)*frameWidth;

		if((anchor & Utils.ANCHOR_HCENTER) != 0)
		{
			x -= frameWidth/2;
		}
		else
		if((anchor & Utils.ANCHOR_RIGHT) != 0)
		{
			x -= frameWidth;
		}
		
		if((anchor & Utils.ANCHOR_BOTTOM) != 0)
		{
			y -= frameHeight;
		}
		else
		if((anchor & Utils.ANCHOR_VCENTER) != 0)
		{
			y -= frameHeight/2;
		}
		g.drawImage(masterImage, x, y, x+frameWidth, y+frameHeight, cell, row, cell+frameWidth, row+frameHeight, null);		
	}
	
	public void paint(Graphics g, int frame, int x, int y)
	{
		paint(g, frame, x, y, 0);
	}	
}
